/**
 * @file index.tsx
 * @description 我的
 */
import React, {useEffect,useState,} from 'react';
import { Alert } from 'react-native';
import {useDispatch, useSelector} from 'react-redux';
import rootReducer from '../../redux/reducers';
import { setUserInfo } from "../../redux/reducers/userReducer";
import {Box, HStack, Avatar, Text, Button, Stack, Icon,Center,useToast,} from 'native-base';
import HeaderScreen from '../../components/header';
import AntDesign from 'react-native-vector-icons/AntDesign';
import Sound from 'react-native-sound';
import { useMount } from "ahooks";
import * as request from "../../request/common";
import storage from "../../utils/storage";
import { isEmpty, } from "../../utils/untils";
import {useFocusEffect} from '@react-navigation/native';

const MineScreen: React.FC<ComponentProp> = ({navigation}) => {
  const [successSound, setSuccessSound] = useState<any>(); // 成功声音
  const [failSound, setFailSound] = useState<any>(); // 失败声音
  const [isLoading, setIsLoading] = useState(false);
  const toast = useToast();

  // redex
  const userInfo: any = useSelector(
    (state: ReturnType<typeof rootReducer>) => state.userInfo.user,
  );
  const dispatch = useDispatch();

  // 生命周期
  useMount(async () => {
    console.log('初始化完成！！！！');
    // 初始化声音
    Sound.setCategory('Playback'); // 设置音频播放类型
    // 创建音频对象
    const successSound = new Sound(
      'successSound.mp3',
      Sound.MAIN_BUNDLE,
      error => {
        if (error) {
          console.log('声音加载失败', error);
          return;
        }
        setSuccessSound(successSound);
        // 声音加载成功
        console.log('声音加载成功');
      },
    );
    const failSound = new Sound('failSound.mp3', Sound.MAIN_BUNDLE, error => {
      if (error) {
        console.log('声音加载失败', error);
        return;
      }
      setFailSound(failSound);
      // 声音加载成功
      console.log('声音加载成功');
    });
  });
  /**
   * 导航获取焦点、失去焦点
   */
   useFocusEffect(
    React.useCallback(() => {
      console.log('屏幕获取焦点');
      checkUserIsLogin();
      return () => {
        console.log('屏幕失去焦点');
      };
    }, []),
  );

  /******方法******/

  // 用户是否登录
  const checkUserIsLogin = async () => {
    let localUserInfo = userInfo;
    console.log(localUserInfo);
    if (isEmpty(localUserInfo)) {
      let storageUserInfo =
        (await storage
          .load({key: 'userInfo'})
          .then(user => user)
          .catch(() => {})) || {};
      if (isEmpty(storageUserInfo)) {
        Alert.alert(
          '提示',
          '您好,当前未登录,请登录后使用',
          [
            {
              text: '登录',
              onPress: () => {
                navigation && navigation.navigate('Login');
              },
            },
          ],
          {cancelable: false},
        );
      } else {
        dispatch(setUserInfo(storageUserInfo));
      }
    }
  };

  /**
   * 退出
   */
  const handleLogout = () => {
    setIsLoading(true);
    request.logout(userInfo?.user_id).then((response: any) => {
      if (response.code == 40020) {
        dispatch(setUserInfo({}));
        storage.save({key: 'userInfo', data: {}});
        toast.show({
          placement: "top",
          description: '退出成功',
        });
        navigation && navigation.navigate('Login');
      } else {
        toast.show({
          placement: "top",
          description: response?.message || '退出失败',
        });
      }
      setIsLoading(false);
    });
  };

  return (
    <Box bg="gray.100" borderRadius="md" flex={1} w="100%" h="100%">
      <HeaderScreen leftBtn={false} navigation={navigation}></HeaderScreen>
      <HStack alignItems="center" pl="6%" pb="4%" space={2} bg="#4F94F9">
        <Avatar
          bg="green.500"
          source={require('../../assets/images/mine_header.png')}></Avatar>
        <Text color="warmGray.100" bold>
          {userInfo?.real_name || ''}
        </Text>
      </HStack>
      <HStack w="100%" h="4" bg="muted.150"></HStack>
      <HStack
        justifyContent="space-between"
        mx="6"
        mt="6"
        pb="4"
        borderBottomWidth="0.3"
        borderColor="muted.300">
        <Stack direction="row" space={1} alignItems="center">
          <Icon as={AntDesign} name="user" color="coolGray.600" />
          <Text color="coolGray.600">账号</Text>
        </Stack>
        <Text color="coolGray.600">{userInfo?.user_name || ''}</Text>
      </HStack>
      <HStack
        justifyContent="space-between"
        mx="6"
        mt="6"
        pb="4"
        borderBottomWidth="0.3"
        borderColor="muted.300">
        <Stack direction="row" space={1} alignItems="center">
          <Icon
            as={AntDesign}
            name="infocirlceo"
            color="coolGray.500"
            _dark={{
              color: 'warmGray.50',
            }}
          />
          <Text color="coolGray.600">版本</Text>
        </Stack>
        <Text color="coolGray.600">V1.1.6</Text>
      </HStack>
      <Center mt="20">
        <Button
          onPress={handleLogout}
          isLoadingText="退出中..."
          w="80%"
          mt="6"
          bg="#4F94F9"
          _pressed={{bg: '#4F94F9'}}>
          退出
        </Button>
      </Center>
    </Box>
  );
};

export default MineScreen;
